package main.com.votes.controller;


import main.com.votes.dao.ArticleDao;
import main.com.votes.dao.OptionDao;
import main.com.votes.dao.VoteDao;
import main.com.votes.model.Article;
import main.com.votes.model.Option;
import main.com.votes.model.Vote;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet("/attendVoteServlet")
public class AttendVoteServlet extends HttpServlet {
    ArticleDao articleDao = new ArticleDao();

    OptionDao optionDao = new OptionDao();

    VoteDao voteDao = new VoteDao();


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int articleid = Integer.parseInt(req.getParameter("articleid"));
//        投票信息
        Article article=articleDao.getById(articleid);


//        选详信息
        List<Option> options=optionDao.getByArticleId(articleid);

        req.setAttribute("article", article);
        req.setAttribute("options",options);

        req.getRequestDispatcher("admin/cytp.jsp").forward(req, resp);

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取参数
        String articleId = request.getParameter("articleid");
        String type = request.getParameter("type"); // 获取投票类型
        String[] optionIds = null;

        if ("0".equals(type)) {
            // 单选
            optionIds = new String[]{request.getParameter("radio")};
        } else {
            // 多选
            optionIds = request.getParameterValues("chbox");
        }

        // 处理投票
        if (articleId != null && optionIds != null) {
            try {
                int articleIdInt = Integer.parseInt(articleId);
                for (String optionId : optionIds) {
                    int optionIdInt = Integer.parseInt(optionId);
                    voteDao.addVote(articleIdInt, optionIdInt, request);
                }
                request.setAttribute("msg", "投票成功！");
            } catch (NumberFormatException e) {
                request.setAttribute("msg", "投票失败，参数错误！");
            }
        } else {
            request.setAttribute("msg", "投票失败，未选择任何选项！");
        }
        // 请求转发到结果页面
        request.getRequestDispatcher("/articleListServlet").forward(request, response);
    }
}
